<template>
  <div class="login" :style="'background-image:url('+ Background +');'">

    <el-form ref="loginForm" class="login-form" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px">
      <div class="title">柯桥区建设集团<br />企业级项目数字化管理平台</div>

      <div style="margin-top: 48px">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <i slot="prefix" class="iconfont  icon-zhanghao">
            </i>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin" show-password>
            <i slot="prefix" class="iconfont icon-anquanguanli3">
            </i>
          </el-input>
        </el-form-item>

        <el-form-item prop="code" class="rowA">
          <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" @keyup.enter.native="handleLogin">
            <i slot="prefix" class="iconfont icon-xiugai-copy">
            </i>
          </el-input>
          <div class="login-code">
            <img class="login-img" :src="codeUrl" @click="getCode">
          </div>
        </el-form-item>

        <el-checkbox v-model="loginForm.rememberMe" style="margin:10px 0 30px;">
          <span class="login-checkbox-text">记住密码</span>
        </el-checkbox>

        <el-form-item class="rowB">
          <el-button class="login-btn" :loading="loading" size="large" type="primary" @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </div>
      <!--  底部 -->
      <div v-if="$store.state.settings.showFooter" id="el-login-footer">
        <span v-html="$store.state.settings.footerTxt" />
        <span> ⋅ </span>
        <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a>
      </div>
    </el-form>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import Config from '@/settings'
import { getCodeImg, qywxLogin } from '@/api/login'
import Cookies from 'js-cookie'
import Background from '@/assets/images/background.png'

export default {
  name: 'Login',
  data() {
    return {
      Background: Background,
      codeUrl: '',
      cookiePass: '',
      activeName: 'first',
      timer: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
      },
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // 获取验证码
    this.getCode()
    // 获取用户名密码等Cookie
    this.getCookie()
    // token 过期提示
    this.point()
  },
  methods: {
    tabClick(tab) {
      const name = tab.name
      switch (name) {
        case 'fourth':
          this.ddLogin()
          break;
      }
    },
    ddLogin() {
      let param = 'DINGTALK'
      qywxLogin(param).then(res => {
        const url = res.data.redirectUri
        const appId = res.data.clientId
        let goto = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appId}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`
        DDLogin({
          id: "ddLogin",
          goto: encodeURIComponent(goto),
          style: "border:none;background-color:#FFFFFF;",
          width: "200",
          height: "400"
        });

        var handleMessage = function(event) {
          var origin = event.origin;
          if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
            var loginTmpCode = event.data;
            //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
            window.location.href = `${goto}&loginTmpCode=${loginTmpCode}`
          }
        };
        if (typeof window.addEventListener != 'undefined') {
          window.addEventListener('message', handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
          window.attachEvent('onmessage', handleMessage);
        }
      })
    },
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? '' : password
      password = password === undefined ? this.loginForm.password : password
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: ''
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        }
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password)
        }
        if (valid) {
          this.loading = true
          if (user.rememberMe) {
            Cookies.set('username', user.username, { expires: Config.passCookieExpires })
            Cookies.set('password', user.password, { expires: Config.passCookieExpires })
            Cookies.set('rememberMe', user.rememberMe, { expires: Config.passCookieExpires })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch('Login', user).then(() => {
            // this.$router.push({ path: this.redirect || '/' })
            this.$router.push('/')
          }).catch(() => {
            this.loading = false
            this.getCode()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    point() {
      const point = Cookies.get('point') !== undefined
      if (point) {
        this.$notify({
          title: '提示',
          message: '当前登录状态已过期，请重新登录！',
          type: 'warning',
          duration: 5000
        })
        Cookies.remove('point')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  height: 100%;
  background-size: cover;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.title {
  font-size: 37px;
  font-family: Microsoft YaHei-Bold, Microsoft YaHei;
  font-weight: bold;
  line-height: 1.25;
  color: #1766d3;
  text-align: center;
}

#ddLogin {
  margin-top: 20px;
  text-align: center;
  height: 400px;
}

.login-form {
  width: 637px;
  background: #ffffffb5;
  border-radius: 27px;
  padding: 124px 66px;

  ::v-deep .el-input {
    // width: 100%;
    height: 53px;
    line-height: 53px;
    input {
      height: 53px;
      line-height: 53px;
      padding-left: 40px;
      border-radius: 10px 10px 10px 10px;
    }
  }
  ::v-deep .el-input__prefix {
    left: 10px;
  }
  .register-btn {
    margin-top: 25px;
    margin-left: 0px;
  }
  .iconfont {
    font-size: 18px;
  }
  .rowA {
    ::v-deep .el-form-item__content {
      display: flex;
      align-items: center;
    }
    ::v-deep .el-input {
      flex: 1;
    }
  }
  .rowB {
    ::v-deep .el-form-item__content {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.login-code {
  width: 142px;
  height: 53px;
  margin-left: 27px;
  .login-img {
    width: 100%;
    height: 51px;
    border-radius: 10px;
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-btn {
  width: 313px;
  height: 71px;
  background: linear-gradient(260deg, #2b7bff 0%, #063bc3 100%);
  border-radius: 36px;
  color: white;
  font-size: 25px;
  &:active {
    opacity: 0.8;
  }
}

.login-checkbox-text {
  height: 17px;
  font-size: 19px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  color: #606266;
}
</style>
